<!DOCTYPE html> 
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>续费链接共享</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #4e73df;
        }
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f8f9fc;
        }
        .header {
            background-color: var(--primary-color);
            color: white ;
            padding: 1.5rem 0;
            margin-bottom: 2rem;
        }
        .link-card {
            transition: all 0.3s;
            border-left: 0.25rem solid var(--primary-color);
        }
        .link-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 1.5rem 0 rgba(58, 59, 69, 0.2);
        }
        .badge-category {
            background-color: #f6c23e;
        }
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        .search-box {
            position: relative;
        }
        .search-box input {
            padding-left: 2.5rem;
        }
        .search-box i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
        }
        .category-badge {
            cursor: pointer;
            margin-right: 5px;
            margin-bottom: 5px;
            display: inline-flex;
            align-items: center;
        }
        .category-badge:hover {
            opacity: 0.8;
        }
        .fixed-bottom {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            z-index: 1000;
        }
        .welcome-section {
            background-color: #e9ecef;
            border-radius: 0.5rem;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        .delete-category {
            cursor: pointer;
            margin-left: 5px;
        }
        .card-footer .btn {
            margin-left: 5px;
        }
        .loading {
            text-align: center;
            padding: 2rem;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-12">
                    <h1>续费链接共享</h1>
                    <p class="mb-0">国内、国外续费</p>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- 欢迎提示 -->
        <div class="welcome-section">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h4>续费链接共享</h4>
                    <p class="mb-0">国内、国外续费</p>
                </div>
                <div class="col-md-4 text-md-end">
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newLinkModal">
                        <i class="fas fa-plus"></i> 添加新链接
                    </button>
                </div>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" class="form-control" placeholder="搜索链接..." id="searchInput">
                </div>
            </div>
            <div class="col-md-6">
                <div class="d-flex">
                    <select class="form-select me-2" id="categoryFilter">
                        <option value="">所有分类</option>
                    </select>
                    <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#categoryModal">
                        <i class="fas fa-tags"></i> 管理分类
                    </button>
                </div>
            </div>
        </div>

        <!-- 链接展示区 -->
        <div class="row" id="linksContainer">
            <div class="col-12 loading">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">正在从LeanCloud加载数据...</p>
            </div>
        </div>

        <!-- 添加链接按钮 -->
        <div class="fixed-bottom">
            <button class="btn btn-primary btn-lg rounded-circle shadow" data-bs-toggle="modal" data-bs-target="#newLinkModal">
                <i class="fas fa-plus"></i>
            </button>
        </div>
    </div>

    <!-- 新建链接模态框 -->
    <div class="modal fade" id="newLinkModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加新链接</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="linkForm">
                        <div class="mb-3">
                            <label for="linkTitle" class="form-label">标题</label>
                            <input type="text" class="form-control" id="linkTitle" required>
                        </div>
                        <div class="mb-3">
                            <label for="linkUrl" class="form-label">URL</label>
                            <input type="url" class="form-control" id="linkUrl" required>
                        </div>
                        <div class="mb-3">
                            <label for="linkCategory" class="form-label">分类</label>
                            <select class="form-select" id="linkCategory" required>
                                <option value="">选择分类</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="linkDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="linkDescription" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveLinkBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑链接模态框 -->
    <div class="modal fade" id="editLinkModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑链接</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editLinkForm">
                        <input type="hidden" id="editLinkId">
                        <div class="mb-3">
                            <label for="editLinkTitle" class="form-label">标题</label>
                            <input type="text" class="form-control" id="editLinkTitle" required>
                        </div>
                        <div class="mb-3">
                            <label for="editLinkUrl" class="form-label">URL</label>
                            <input type="url" class="form-control" id="editLinkUrl" required>
                        </div>
                        <div class="mb-3">
                            <label for="editLinkCategory" class="form-label">分类</label>
                            <select class="form-select" id="editLinkCategory" required>
                                <option value="">选择分类</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="editLinkDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="editLinkDescription" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="updateLinkBtn">更新</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 分类管理模态框 -->
    <div class="modal fade" id="categoryModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">分类管理</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-4">
                        <h5>添加新分类</h5>
                        <form id="addCategoryForm" class="row g-3">
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="newCategoryName" placeholder="分类名称" required>
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary">添加</button>
                            </div>
                        </form>
                    </div>
                    <div>
                        <h5>现有分类</h5>
                        <div id="categoriesList" class="d-flex flex-wrap">
                            <!-- 分类列表将在这里动态生成 -->
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 脚本引用 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- LeanCloud SDK -->
    <script src="https://cdn.jsdelivr.net/npm/leancloud-storage@4.13.2/dist/av-min.js"></script>
    <script>
        // LeanCloud 初始化
        const APP_ID = 's9ykp0a8zYsC9uulPMOmxlTF-gzGzoHsz';
        const APP_KEY = 'bmWvszerTi1uLGhAubFVGL8O';
        
        AV.init({
            appId: APP_ID,
            appKey: APP_KEY,
            serverURLs: 'https://s9ykp0a8.lc-cn-n1-shared.com'
        });

        // 数据模型
        const Link = AV.Object.extend('Link');
        const Category = AV.Object.extend('Category');

        // 全局数据
        let links = [];
        let categories = [];

        // DOM元素
        const linksContainer = document.getElementById('linksContainer');
        const searchInput = document.getElementById('searchInput');
        const categoryFilter = document.getElementById('categoryFilter');
        const saveLinkBtn = document.getElementById('saveLinkBtn');
        const updateLinkBtn = document.getElementById('updateLinkBtn');
        const addCategoryForm = document.getElementById('addCategoryForm');
        const categoriesList = document.getElementById('categoriesList');
        const linkCategorySelect = document.getElementById('linkCategory');
        const editLinkCategorySelect = document.getElementById('editLinkCategory');
        const newCategoryNameInput = document.getElementById('newCategoryName');

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            // 加载初始数据
            loadInitialData();
            
            // 保存链接事件
            saveLinkBtn.addEventListener('click', saveLink);
            
            // 更新链接事件
            updateLinkBtn.addEventListener('click', updateLink);

            // 搜索功能
            searchInput.addEventListener('input', filterLinks);

            // 分类筛选
            categoryFilter.addEventListener('change', filterLinks);
            
            // 添加分类事件
            addCategoryForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const categoryName = newCategoryNameInput.value.trim();
                if (categoryName) {
                    addCategory(categoryName);
                    newCategoryNameInput.value = '';
                }
            });

            // 使用事件委托处理删除分类按钮
            categoriesList.addEventListener('click', function(e) {
                if (e.target.classList.contains('delete-category')) {
                    const categoryBadge = e.target.closest('.category-badge');
                    if (categoryBadge) {
                        const category = categoryBadge.querySelector('.category-name').textContent;
                        deleteCategory(category);
                    }
                }
            });
        });

        // 加载初始数据
        async function loadInitialData() {
            try {
                await Promise.all([loadLinks(), loadCategories()]);
                updateCategorySelectors();
                renderCategoriesList();
            } catch (error) {
                console.error('加载数据失败:', error);
                Swal.fire({
                    title: '加载失败',
                    text: '无法从服务器加载数据，请检查网络连接',
                    icon: 'error',
                    confirmButtonText: '好的'
                });
            }
        }

        // 从LeanCloud加载链接
        async function loadLinks() {
            try {
                const query = new AV.Query('Link');
                query.include('category');
                query.descending('createdAt');
                const results = await query.find();
                
                links = results.map(item => ({
                    id: item.id,
                    title: item.get('title'),
                    url: item.get('url'),
                    category: item.get('category'),
                    description: item.get('description') || '',
                    dateAdded: item.createdAt
                }));
                
                renderLinks(links);
            } catch (error) {
                console.error('加载链接失败:', error);
                throw error;
            }
        }

        // 从LeanCloud加载分类
        async function loadCategories() {
            try {
                const query = new AV.Query('Category');
                const results = await query.find();
                
                if (results.length === 0) {
                    // 如果没有分类，创建默认分类
                    const defaultCategories = ['开发', '设计', '市场', '文档', '工具'];
                    for (const catName of defaultCategories) {
                        const category = new Category();
                        category.set('name', catName);
                        await category.save();
                    }
                    // 重新加载分类
                    return loadCategories();
                }
                
                categories = results.map(item => item.get('name'));
            } catch (error) {
                console.error('加载分类失败:', error);
                throw error;
            }
        }

        // 更新分类选择器
        function updateCategorySelectors() {
            // 更新筛选器的分类选项
            categoryFilter.innerHTML = '<option value="">所有分类</option>';
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category;
                option.textContent = category;
                categoryFilter.appendChild(option);
            });
            
            // 更新链接表单的分类选项
            linkCategorySelect.innerHTML = '<option value="">选择分类</option>';
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category;
                option.textContent = category;
                linkCategorySelect.appendChild(option);
            });
            
            // 更新编辑链接表单的分类选项
            editLinkCategorySelect.innerHTML = '<option value="">选择分类</option>';
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category;
                option.textContent = category;
                editLinkCategorySelect.appendChild(option);
            });
        }

        // 渲染分类列表
        function renderCategoriesList() {
            categoriesList.innerHTML = '';
            categories.forEach(category => {
                const badge = document.createElement('span');
                badge.className = 'badge bg-primary category-badge me-2 mb-2';
                badge.innerHTML = `
                    <span class="category-name">${category}</span>
                    <i class="fas fa-times delete-category ms-1"></i>
                `;
                categoriesList.appendChild(badge);
            });
        }

        // 添加分类到LeanCloud
        async function addCategory(categoryName) {
            if (categories.includes(categoryName)) {
                Swal.fire({
                    title: '分类已存在',
                    text: `分类 "${categoryName}" 已经存在`,
                    icon: 'warning',
                    confirmButtonText: '好的'
                });
                return;
            }
            
            try {
                const category = new Category();
                category.set('name', categoryName);
                await category.save();
                
                categories.push(categoryName);
                updateCategorySelectors();
                renderCategoriesList();
                
                Swal.fire({
                    title: '添加成功',
                    text: `分类 "${categoryName}" 已添加`,
                    icon: 'success',
                    confirmButtonText: '好的'
                });
            } catch (error) {
                console.error('添加分类失败:', error);
                Swal.fire({
                    title: '添加失败',
                    text: '无法添加分类，请重试',
                    icon: 'error',
                    confirmButtonText: '好的'
                });
            }
        }

        // 从LeanCloud删除分类
        async function deleteCategory(categoryName) {
            // 检查是否有链接使用此分类
            const linksUsingCategory = links.filter(link => link.category === categoryName);
            
            if (linksUsingCategory.length > 0) {
                Swal.fire({
                    title: '无法删除',
                    html: `分类 "${categoryName}" 正在被 ${linksUsingCategory.length} 个链接使用。<br>请先修改这些链接的分类后再删除。`,
                    icon: 'error',
                    confirmButtonText: '好的'
                });
                return;
            }
            
            try {
                const query = new AV.Query('Category');
                query.equalTo('name', categoryName);
                const result = await query.first();
                
                if (result) {
                    await result.destroy();
                    categories = categories.filter(cat => cat !== categoryName);
                    updateCategorySelectors();
                    renderCategoriesList();
                    
                    Swal.fire({
                        title: '删除成功',
                        text: `分类 "${categoryName}" 已删除`,
                        icon: 'success',
                        confirmButtonText: '好的'
                    });
                }
            } catch (error) {
                console.error('删除分类失败:', error);
                Swal.fire({
                    title: '删除失败',
                    text: '无法删除分类，请重试',
                    icon: 'error',
                    confirmButtonText: '好的'
                });
            }
        }

        // 渲染链接卡片
        function renderLinks(linksToRender) {
            linksContainer.innerHTML = '';
            
            if (linksToRender.length === 0) {
                linksContainer.innerHTML = `
                    <div class="col-12 text-center py-5">
                        <i class="fas fa-link fa-3x text-muted mb-3"></i>
                        <h4 class="text-muted">暂无链接</h4>
                        <p>点击右下角的"+"按钮添加第一个链接</p>
                    </div>
                `;
                return;
            }
            
            linksToRender.forEach(link => {
                const linkCard = document.createElement('div');
                linkCard.className = 'col-md-4 mb-4';
                linkCard.innerHTML = `
                    <div class="card link-card h-100">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <h5 class="card-title">${link.title}</h5>
                                <span class="badge badge-category bg-primary">${link.category}</span>
                            </div>
                            <p class="card-text text-muted">${link.description || '暂无描述'}</p>
                            <a href="${link.url}" target="_blank" class="btn btn-sm btn-outline-primary">访问链接</a>
                        </div>
                        <div class="card-footer bg-transparent">
                            <small class="text-muted">添加于 ${new Date(link.dateAdded).toLocaleDateString()}</small>
                            <div class="float-end">
                                <button class="btn btn-sm btn-outline-warning edit-link" data-id="${link.id}">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-danger delete-link" data-id="${link.id}">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                linksContainer.appendChild(linkCard);
            });
            
            // 添加删除事件
            document.querySelectorAll('.delete-link').forEach(btn => {
                btn.addEventListener('click', function() {
                    const linkId = this.getAttribute('data-id');
                    deleteLink(linkId);
                });
            });
            
            // 添加编辑事件
            document.querySelectorAll('.edit-link').forEach(btn => {
                btn.addEventListener('click', function() {
                    const linkId = this.getAttribute('data-id');
                    editLink(linkId);
                });
            });
        }
        
        // 保存链接到LeanCloud
        async function saveLink() {
            const title = document.getElementById('linkTitle').value;
            const url = document.getElementById('linkUrl').value;
            const category = document.getElementById('linkCategory').value;
            const description = document.getElementById('linkDescription').value;
            
            if (!title || !url || !category) {
                Swal.fire({
                    title: '信息不完整',
                    text: '请填写标题、URL和分类',
                    icon: 'error',
                    confirmButtonText: '好的'
                });
                return;
            }
            
            try {
                const link = new Link();
                link.set('title', title);
                link.set('url', url);
                link.set('category', category);
                link.set('description', description);
                
                await link.save();
                
                // 重新加载链接列表
                await loadLinks();
                
                // 重置表单并关闭模态框
                document.getElementById('linkForm').reset();
                bootstrap.Modal.getInstance(document.getElementById('newLinkModal')).hide();
                
                Swal.fire({
                    title: '链接添加成功!',
                    icon: 'success',
                    confirmButtonText: '好的'
                });
            } catch (error) {
                console.error('保存链接失败:', error);
                Swal.fire({
                    title: '保存失败',
                    text: '无法保存链接，请重试',
                    icon: 'error',
                    confirmButtonText: '好的'
                });
            }
        }
        
        // 编辑链接
        function editLink(id) {
            const link = links.find(link => link.id === id);
            if (!link) return;
            
            // 填充表单数据
            document.getElementById('editLinkId').value = link.id;
            document.getElementById('editLinkTitle').value = link.title;
            document.getElementById('editLinkUrl').value = link.url;
            document.getElementById('editLinkCategory').value = link.category;
            document.getElementById('editLinkDescription').value = link.description || '';
            
            // 显示编辑模态框
            const editModal = new bootstrap.Modal(document.getElementById('editLinkModal'));
            editModal.show();
        }
        
        // 更新链接到LeanCloud
        async function updateLink() {
            const id = document.getElementById('editLinkId').value;
            const title = document.getElementById('editLinkTitle').value;
            const url = document.getElementById('editLinkUrl').value;
            const category = document.getElementById('editLinkCategory').value;
            const description = document.getElementById('editLinkDescription').value;
            
            if (!title || !url || !category) {
                Swal.fire({
                    title: '信息不完整',
                    text: '请填写标题、URL和分类',
                    icon: 'error',
                    confirmButtonText: '好的'
                });
                return;
            }
            
            try {
                const link = AV.Object.createWithoutData('Link', id);
                link.set('title', title);
                link.set('url', url);
                link.set('category', category);
                link.set('description', description);
                
                await link.save();
                
                // 重新加载链接列表
                await loadLinks();
                
                // 关闭模态框
                bootstrap.Modal.getInstance(document.getElementById('editLinkModal')).hide();
                
                Swal.fire({
                    title: '链接更新成功!',
                    icon: 'success',
                    confirmButtonText: '好的'
                });
            } catch (error) {
                console.error('更新链接失败:', error);
                Swal.fire({
                    title: '更新失败',
                    text: '无法更新链接，请重试',
                    icon: 'error',
                    confirmButtonText: '好的'
                });
            }
        }
        
        // 从LeanCloud删除链接
        async function deleteLink(id) {
            Swal.fire({
                title: '确定要删除吗?',
                text: "删除后将无法恢复此链接",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: '删除',
                cancelButtonText: '取消'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const link = AV.Object.createWithoutData('Link', id);
                        await link.destroy();
                        
                        // 重新加载链接列表
                        await loadLinks();
                    } catch (error) {
                        console.error('删除链接失败:', error);
                        Swal.fire({
                            title: '删除失败',
                            text: '无法删除链接，请重试',
                            icon: 'error',
                            confirmButtonText: '好的'
                        });
                    }
                }
            });
        }
        
        // 筛选链接
        function filterLinks() {
            const searchTerm = searchInput.value.toLowerCase();
            const selectedCategory = categoryFilter.value;
            
            const filteredLinks = links.filter(link => {
                const matchesSearch = link.title.toLowerCase().includes(searchTerm) || 
                                     (link.description && link.description.toLowerCase().includes(searchTerm));
                
                const matchesCategory = selectedCategory === '' || link.category === selectedCategory;
                
                return matchesSearch && matchesCategory;
            });
            
            renderLinks(filteredLinks);
        }
    </script>
</body>
</html>